package cn1shared.net;

import java.io.InputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import json_simpler.JsonValue;
import json_simpler.parser.ParseException;


public class JsonCon {
	final DataInputStream in;
	final DataOutputStream out;

	JsonCon(DataInputStream in,DataOutputStream out) {
		this.in = in;
		this.out = out;
	}

	public void close() throws IOException {
		in.close();
		out.close();
	}

	void send(List<Object> json,InputStream... ins) throws IOException {
		String s = JsonValue.toJsonString(json);
		out.writeUTF(s);
		for( InputStream in : ins ) {
			byte[] a = new byte[8192];
			int n;
			while( (n=in.read(a)) != -1 ) {
				out.write(a,0,n);
			}
			in.close();
		}
		out.flush();
	}

	List<Object> receive() throws IOException {
		String s = in.readUTF();
		try {
			@SuppressWarnings("unchecked")
			List<Object> response = (List<Object>)JsonValue.parse(s);
			return response;
		} catch(ParseException e) {
			throw new RuntimeException(e.toString());
		}
	}

	public InputStream getLimitedInputStream(long length) {
		return new LimitedInputStream(in,length);
	}

	public static String mobileCallsHost(String netId) {
		return netId + " mobile calls host";
	}

	public static String hostCallsMobile(String netId) {
		return netId + " host calls mobile";
	}

}
